<template>
  <!--Dialog-->
  <Dialog v-model="modelValue">
    <el-form
      :status-icon="true"
      :inline="true"
      :model="updateForm"
      label-width="auto"
      ref="updateFormRef"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="名称"
            prop="title"
            :rules="[{ required: true, message: '请输入公告标题' }]"
          >
            <el-input v-model="updateForm.title" placeholder="请输入公告标题" maxlength="256" />
          </el-form-item>
          <el-form-item
            label="发布类型"
            prop="publishType"
            :rules="[{ required: true, message: '请选择发布类型' }]"
          >
            <PublishTypeComponent v-model="updateForm.publishType" />
            <div class="date" v-if="updateForm.publishType === PublishType.Delay">
              <el-form-item
                prop="publishTime"
                :rules="[{ required: true, message: '请选择发布时间' }]"
              >
                <PublishTimeComponent v-model="updateForm.publishTime" />
              </el-form-item>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="公告内容"
            prop="content"
            :rules="[{ required: true, message: '请选择输入公共内容' }]"
          >
            <Editor
              v-model="defaultHtml"
              ref="editorRef"
              @change="change"
              :height="300"
              :editorConfig="{ placeholder: '请输入公告内容...' }"
              :toolbarConfig="{ excludeKeys: ['uploadVideo', 'insertVideo', 'editVideoSize'] }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSavue(updateFormRef)" :loading="isLoading"
        >保存</el-button
      >
      <el-button @click="onClose">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { updateAsync, getAsync } from '@/utils/api/announcement/index';
import { Dialog } from '@/components/dialog/index';
import { PublishTypeComponent } from '../../publishType/index';
import { PublishTimeComponent } from '../../publishTime/index';
import { Editor, type EditorExpose } from '@/components/editor';
import { propTypes } from '@/utils/propTypes';
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { PublishType, type AnnouncementUpdateInputDto } from '@/utils/api/announcement/type';
import type { ValidateFieldsError } from 'async-validator/dist-types';
import type { IDomEditor } from '@wangeditor/editor';

let $emit = defineEmits(['update:refresh']);
// 刷新父组件
const refresh = () => {
  $emit('update:refresh');
};

const props = defineProps({
  id: propTypes.string
});

// 控制组件隐藏与显示
const modelValue = defineModel<boolean>(propTypes.bool.def(false));
const close = () => {
  modelValue.value = false;
};
// 保存Loading效果状态
const isLoading = ref<boolean>(false);

// 关闭
const onClose = () => {
  //触发自定义事件
  close();
};

// 保存
const onSavue = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) {
    return;
  }

  // 提交验证
  await formEl.validate(
    async (isValid: boolean, invalidFields?: ValidateFieldsError): Promise<void> => {
      if (isValid) {
        try {
          isLoading.value = true;

          await updateAsync(props.id, updateForm.value);

          // 关闭弹窗
          close();
          // 提示成功
          ElMessage({
            showClose: true,
            message: '添加成功',
            type: 'success'
          });
          // 刷新父组件
          refresh();
        } catch (error) {
          if (error) {
            let msg: string = (error as Error).message;
            if (msg) {
              ElMessage({
                showClose: true,
                message: (error as Error).message,
                type: 'error'
              });
            }
          }
        } finally {
          isLoading.value = false;
        }
      } else {
        console.log('error submit!', invalidFields);
      }
    }
  );
};

// 组件实例
const updateFormRef = ref<FormInstance>();
// 添加对象
const updateForm = ref<AnnouncementUpdateInputDto>({
  publishTime: new Date(),
  title: '',
  content: '',
  publishType: PublishType.Immediately
});

const defaultHtml = ref('');
const editorRef = ref<typeof Editor & EditorExpose>();
const change = (editor: IDomEditor) => {
  updateForm.value.content = editor.getHtml();
};

onMounted(async () => {
  const announcement = await getAsync(props.id);
  updateForm.value.content = announcement.content;
  updateForm.value.title = announcement.title;
  updateForm.value.publishType = announcement.publishType;
  updateForm.value.publishTime = announcement.publishTime;
  defaultHtml.value = announcement.content;
});
</script>
<style scoped lang="scss">
.date {
  margin-left: 15px;
}
</style>
